import numpy as np
from bert_serving.client import BertClient
import pandas as pd


# 计算余弦相似度
def cos(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))


# 使用bert-as-serving将句子编码为句向量
def embed_sentences_by_bert_serving(sent_list):
    bc = BertClient(port=5551, port_out=5552)
    return bc.encode(sent_list)


# 根据相似度排序
def sort_standard_names(standard_names, standard_names_embedd, checked_names_embedd):
    sim = {}
    for idx, name in enumerate(standard_names):
        sim[name] = cos(standard_names_embedd[idx], checked_names_embedd)
    res = sorted(sim.items(), key=lambda item: item[1], reverse=True)
    return res


# 读取xlsx文件，将第一列标准名称和第二列被查重名称转换为数据
def read_xlsx(url):
    # standard_names存标准名称，checked_names存被查重名称
    standard_names = []
    checked_names = []

    df = pd.read_excel(url)
    print(df.columns)

    try:
        df_0 = df['标准名称']
        df_1 = df['被查重名称']
        standard_names = df_0.dropna().values.tolist()
        checked_names = df_1.dropna().values.tolist()
    except KeyError:
        print("表格必须包含'标准名称'及'被查重名称'！")

    return standard_names, checked_names
